package com.crazecoder.flutter.iflyad.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.DrawableRes;

import com.crazecoder.flutter.iflyad.BuildConfig;
import com.crazecoder.flutter.iflyad.R;
import com.crazecoder.flutter.iflyad.utils.OAIDUtil;
import com.iflytek.voiceads.IFLYAdSDK;
import com.iflytek.voiceads.IFLYNativeAd;
import com.iflytek.voiceads.config.AdError;
import com.iflytek.voiceads.config.AdKeys;
import com.iflytek.voiceads.conn.NativeDataRef;
import com.iflytek.voiceads.listener.IFLYNativeListener;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


public abstract class NativeSplashAbstractActivity extends Activity {

    private NativeDataRef adItem;
    private String adUnitId;

    private ImageView fullscreenImg;
    private TextView mCountDownText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //隐去状态栏部分（电池等图标和一起修饰部分）
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.splash_native_ad);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
//            String processName = getProcessName();
//            String packageName = getPackageName();
//            if (!packageName.equals(processName) ) {
//                WebView.setDataDirectorySuffix(processName);
//            }
//        }
        OAIDUtil.getInstance(this).init();
        fullscreenImg = this.findViewById(R.id.fullscreen_img);
        mCountDownText = (TextView) findViewById(R.id.count_down_text);
        if (getLaunchBackground() != null)
            fullscreenImg.setBackground(getResources().getDrawable(getLaunchBackground()));
        String appId = getIntent().getStringExtra("appId");
        adUnitId = getIntent().getStringExtra("adUnitId");
        if (TextUtils.isEmpty(appId)) {
            appId = getAppId();
        }
        initSdk(appId);
        if (TextUtils.isEmpty(adUnitId)) {
            adUnitId = getAdUnitId();
        }

        // 如果targetSDKVersion >= 23，就要申请好权限。如果您的App没有适配到Android6.0（即targetSDKVersion < 23），那么只需要在这里直接调用fetchSplashAD接口。
        if (Build.VERSION.SDK_INT >= 23) {
            checkAndRequestPermission();
        } else {
            // 如果是Android6.0以下的机器，默认在安装时获得了所有权限，可以直接调用SDK
            fetchSplashAD();
        }
    }
    private void initSdk(String appid){
        //设置全局参数，可根据需要进行设置，必须在初始化方法前设置
        IFLYAdSDK.setParameter(AdKeys.MAIN_PROCESS_NAME, appid);

        //进行SDK初始化
        IFLYAdSDK.init(this);
    }

    /**
     * ----------非常重要----------
     * <p>
     * Android6.0以上的权限适配简单示例：
     * <p>
     * 如果targetSDKVersion >= 23，那么必须要申请到所需要的权限，再调用广点通SDK，否则广点通SDK不会工作。
     * <p>
     * Demo代码里是一个基本的权限申请示例，请开发者根据自己的场景合理地编写这部分代码来实现权限申请。
     * 注意：下面的`checkSelfPermission`和`requestPermissions`方法都是在Android6.0的SDK中增加的API，如果您的App还没有适配到Android6.0以上，则不需要调用这些方法，直接调用广点通SDK即可。
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void checkAndRequestPermission() {
        List<String> lackedPermission = new ArrayList<String>();
        if (!(checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.READ_PHONE_STATE);
        }

        if (!(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

//        if (!(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
//            lackedPermission.add(Manifest.permission.ACCESS_FINE_LOCATION);
//        }
//        if (!(checkSelfPermission(Manifest.permission.REQUEST_INSTALL_PACKAGES) == PackageManager.PERMISSION_GRANTED)) {
//            lackedPermission.add(Manifest.permission.REQUEST_INSTALL_PACKAGES);
//        }

        // 权限都已经有了，那么直接调用SDK
        if (lackedPermission.size() == 0) {
            fetchSplashAD();
        } else {
            // 请求所缺少的权限，在onRequestPermissionsResult中再看是否获得权限，如果获得权限就可以调用SDK，否则不要调用SDK。
            String[] requestPermissions = new String[lackedPermission.size()];
            lackedPermission.toArray(requestPermissions);
            requestPermissions(requestPermissions, 1024);
        }
    }

    private boolean hasAllPermissionsGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1024 && hasAllPermissionsGranted(grantResults)) {
            fetchSplashAD();
        } else {
            // 如果用户没有授权，那么应该说明意图，引导用户去设置里面授权。
            Toast.makeText(this, "应用缺少必要的权限！请点击\"权限\"，打开所需要的权限。", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
            finish();
        }
    }

    /**
     * 拉取开屏广告，开屏广告的构造方法有3种，详细说明请参考开发者文档。
     *：取值范围[3000, 5000]，设为0表示使用广点通SDK默认的超时时长。
     */
    private void fetchSplashAD() {
        String oaid = OAIDUtil.getInstance(this).getOAID();
        IFLYNativeAd nativeAd = new IFLYNativeAd(getApplicationContext(), adUnitId, splashADListener);
        nativeAd.setParameter(AdKeys.DOWNLOAD_ALERT, true);
        nativeAd.setParameter(AdKeys.APP_VER, "1.0");
        //通过第三方sdk获取，具体参考文档
        nativeAd.setParameter(AdKeys.OAID, oaid);
        nativeAd.setParameter(AdKeys.DEBUG_MODE, BuildConfig.DEBUG);
        nativeAd.loadAd();
    }

    public void showAD() {
        String adUrl = adItem.getImgUrl();
        if (!TextUtils.isEmpty(adUrl)) {
            Log.d("Ad_Android_Demo", adUrl);
            Picasso.with(this).load(adUrl).into(fullscreenImg);
        }else {
            finish();
            return;
        }
        fullscreenImg.setVisibility(View.VISIBLE);
        mCountDownText.setVisibility(View.VISIBLE);
        final CountDownTimer countDownTimer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mCountDownText.setText(String.format(Locale.CHINA, "跳过 %d", millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
//                mCountDownText.setVisibility(View.GONE);
//                fullscreenImg.setVisibility(View.GONE);
                finish();
            }
        };
        countDownTimer.start();

        fullscreenImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adItem.onClick(view);
                countDownTimer.cancel();
                finish();
            }
        });
        mCountDownText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                countDownTimer.cancel();
                finish();
            }
        });

        if (adItem.onExposure(fullscreenImg)) {
            Log.d("Ad_Android_Demo", "onExposure");
        }
    }

    private IFLYNativeListener splashADListener = new IFLYNativeListener() {
        @Override
        public void onAdFailed(AdError error) {
            //注意如果请求广告失败，记录这里的errorcode进行反馈
            Log.d("Ad_Android_Demo", "onAdFailed");
            finish();
        }

        @Override
        public void onAdLoaded(NativeDataRef dataRef) {
            Log.d("Ad_Android_Demo", "onAdLoaded");
            adItem = dataRef;
            showAD();
        }

        @Override
        public void onCancel() {
            Log.d("Ad_Android_Demo", "onCancel");
            finish();
        }


        @Override
        public void onConfirm() {
            Log.d("Ad_Android_Demo", "onConfirm");
            finish();
        }
    };


    /**
     * 开屏页一定要禁止用户对返回按钮的控制，否则将可能导致用户手动退出了App而广告无法正常曝光和计费
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected abstract String getAppId();

    protected abstract String getAdUnitId();

    protected abstract @DrawableRes
    Integer getLaunchBackground();
}
